package com.fivefu.core.gb28181.listner.impl;

import com.alibaba.fastjson.JSON;
import com.fivefu.core.gb28181.listner.SipResponseListener;
import com.fivefu.core.gb28181.listner.SipServerLayer;
import com.fivefu.core.gb28181.pojo.DeviceBean;
import com.fivefu.core.gb28181.utils.SipMessageUtils;
import gov.nist.javax.sip.ResponseEventExt;
import gov.nist.javax.sip.stack.SIPDialog;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.sdp.SdpFactory;
import javax.sdp.SessionDescription;
import javax.sip.InvalidArgumentException;
import javax.sip.ResponseEvent;
import javax.sip.SipException;
import javax.sip.SipFactory;
import javax.sip.address.Address;
import javax.sip.address.SipURI;
import javax.sip.header.CSeqHeader;
import javax.sip.header.UserAgentHeader;
import javax.sip.message.Request;
import javax.sip.message.Response;
import java.io.ByteArrayInputStream;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

@Component
public class InviteResponseListener implements SipResponseListener {

    private Logger logger = LoggerFactory.getLogger(InviteResponseListener.class);

    @Autowired
    private SipServerLayer sipServerLayer;
    @Autowired
    private SipMessageUtils sipMessageUtils;
//    @Autowired
//    private MediaServerLayer mediaServerLayer;

    @Override
    public void process(ResponseEvent responseEvent) throws SipException, ParseException, InvalidArgumentException {
        System.out.println("invite ack");
        try{
            Response response = responseEvent.getResponse();
            System.out.println(response.getStatusCode());
            if (response.getStatusCode() == 200){
                DeviceBean bean = new DeviceBean("34020000002000000002","192.168.0.40",5060,"tcp");

                System.out.println(JSON.toJSONString(response.getContent()));


                String viaTag = "media_viaTag";
                String fromTag = "media_fromTag";
                String toTag = null;
                //sipMessageUtils.sendInviteMessage(bean,"",viaTag,fromTag,toTag,ssrc,"");

                ResponseEventExt event = (ResponseEventExt)responseEvent;
                SipFactory sipFactory = sipServerLayer.getSipFactory();
                SIPDialog dialog = (SIPDialog)event.getDialog();
                CSeqHeader cseq = (CSeqHeader) response.getHeader(CSeqHeader.NAME);
                Request reqAck = dialog.createAck(cseq.getSeqNumber());
                SipURI requestURI = (SipURI) reqAck.getRequestURI();
                String contentString = new String(response.getRawContent());
                // jainSip不支持y=字段， 移除以解析。
                int ssrcIndex = contentString.indexOf("y=");
                // 检查是否有y字段
                SessionDescription sdp;
                if (ssrcIndex >= 0) {
                    //ssrc规定长度为10字节，不取余下长度以避免后续还有“f=”字段
                    String substring = contentString.substring(0, contentString.indexOf("y="));
                    sdp = SdpFactory.getInstance().createSessionDescription(substring);
                } else {
                    sdp = SdpFactory.getInstance().createSessionDescription(contentString);
                }
                requestURI.setUser(sdp.getOrigin().getUsername());
                try {
                    requestURI.setHost(event.getRemoteIpAddress());
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                requestURI.setPort(event.getRemotePort());
                reqAck.setRequestURI(requestURI);

                List<String> agentParam = new ArrayList<>();
                agentParam.add("WVP PRO");
                // TODO 添加版本信息以及日期
                UserAgentHeader userAgentHeader = sipFactory.createHeaderFactory().createUserAgentHeader(agentParam);
                reqAck.addHeader(userAgentHeader);
                Address concatAddress = sipFactory.createAddressFactory().createAddress(sipFactory.createAddressFactory().createSipURI("34020000001180000001", "192.168.0.144"+":"+5060));
                reqAck.addHeader(sipFactory.createHeaderFactory().createContactHeader(concatAddress));
                logger.info("[回复ack] {}-> {}:{} ",requestURI, event.getRemoteIpAddress(), event.getRemotePort());

                dialog.sendAck(reqAck);
                /*SIPDialog dialog = (SIPDialog)responseEvent.getDialog();
                CSeqHeader cseq = (CSeqHeader) response.getHeader(CSeqHeader.NAME);
                Request reqAck = dialog.createAck(cseq.getSeqNumber());
                SipURI requestURI = (SipURI) reqAck.getRequestURI();
                requestURI.setHost(event.getRemoteIpAddress());
                requestURI.setPort(event.getRemotePort());
                reqAck.setRequestURI(requestURI);
                logger.info("向 " + event.getRemoteIpAddress() + ":" + event.getRemotePort() + "回复ack");
                logger.info("reqAck->{}"+reqAck);
                dialog.sendAck(reqAck);*/
            }
        }catch (Exception e){
            logger.error(e.getMessage(),e);
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        sipServerLayer.addSipResponseListener(Request.INVITE,this);
    }
}
